package com.starlink.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.hutool.core.convert.Convert;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageHelper;
import com.starlink.common.enums.BooleanEnum;
import com.starlink.common.enums.FreeEnum;
import com.starlink.context.SessionContext;
import com.starlink.mapper.AddressMapper;
import com.starlink.mapper.FreeCarryModeMapper;
import com.starlink.model.domain.FreeCarryModeDO;
import com.starlink.model.domain.FreeDeliveryTermsDO;
import com.starlink.model.request.FreeDeliveryTermsRequest;
import com.starlink.model.request.mall.FreeTemplateInfoRequest;
import com.starlink.model.util.FreeTemplateConvert;
import com.starlink.model.vo.MallBooksSpecificationVO;
import com.starlink.model.vo.MallPeripheryVO;
import com.starlink.model.vo.book.FreeCarryModeInfoVO;
import com.starlink.model.vo.book.FreeDeliveryTermsInfoVO;
import com.starlink.model.vo.book.FreeTemplateInfoVO;
import com.starlink.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Pageable;
import com.starlink.common.utils.AssertUtil;
import com.starlink.model.dtomapper.FreeTemplateDtoMapper;
import com.starlink.model.domain.FreeTemplateDO;
import com.starlink.mapper.FreeTemplateMapper;
import com.starlink.model.request.FreeTemplateRequest;
import com.starlink.model.vo.FreeTemplateVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import static com.starlink.utils.PageUtils.getOrderBy;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhanghong
 */
@Service
public class FreeTemplateServiceImpl extends ServiceImpl<FreeTemplateMapper, FreeTemplateDO> implements FreeTemplateService {
    @Autowired
    private FreeTemplateMapper freeTemplateMapper;
    @Autowired
    private FreeDeliveryTermsService deliveryTermsService;
    @Autowired
    private FreeCarryModeService carryModeService;
    @Autowired
    private FreeCarryModeMapper carryModeMapper;

    private static final Integer ZERO = 0;
    private static final Integer ONE = 1;

    @Override
    public FreeTemplateVO getByKey(long id) {
        FreeTemplateVO freeTemplateVO = FreeTemplateDtoMapper.INSTANCE.do2VO(getById(id));
        return freeTemplateVO;
    }

    @Override
    public PageInfo<FreeTemplateVO> pageQuery(Pageable pageable,FreeTemplateRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), getOrderBy(pageable.getSort())).setReasonable(true);
        List<FreeTemplateDO> list = freeTemplateMapper.pageQuery(request, request.getPageSize(), request.fetchOffSet());
        List<FreeTemplateVO> freeTemplateVOList = FreeTemplateConvert.buildFreeTemplateVoList(list);
        return new PageInfo(freeTemplateVOList);
    }

    @Override
    public List<FreeTemplateVO> listQuery(FreeTemplateRequest request) {
        List<FreeTemplateDO> list = freeTemplateMapper.selectDOList(FreeTemplateDtoMapper.INSTANCE.request2DO(request));
        List<FreeTemplateVO> freeTemplateVOS = FreeTemplateConvert.buildFreeTemplateVoList(list);
        return freeTemplateVOS;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(FreeTemplateRequest request) {
        save(FreeTemplateDtoMapper.INSTANCE.request2DO(request));
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByKey(FreeTemplateRequest request) {
        AssertUtil.assertNotNull(request.getId(), "id不能为空");
        saveOrUpdate(FreeTemplateDtoMapper.INSTANCE.request2DO(request));
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteDOByIds(String ids) {
        freeTemplateMapper.deleteDOByIds(Convert.toStrArray(ids));
        return true;
    }

    @Override
    public FreeTemplateInfoVO selectFreeTempInfoByFreeTemplateId(Long freeTemplateId) {
        FreeTemplateInfoVO templateInfoVO= freeTemplateMapper.selectFreeTempInfoByFreeTemplateId(freeTemplateId);
        return templateInfoVO;
    }

    @Override
    public FreeCarryModeInfoVO selectDefultTempInfo() {
        return carryModeMapper.selectDefultTempInfo();
    }

    @Override
    public PageInfo<List<FreeTemplateVO>> pagingQuery(FreeTemplateRequest request, Pageable pageable) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), getOrderBy(pageable.getSort())).setReasonable(true);
        List<FreeTemplateVO> list = freeTemplateMapper.pagingQuery(request);
        return new PageInfo(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean editing(FreeTemplateInfoRequest request) {
        Long templateId = request.getTemplateId();
        String tempName = request.getTempName();
        Integer valuationModel = request.getValuationModel();
        if(StringUtils.isEmpty(tempName) || valuationModel == null){
            throw new RuntimeException("名称与计价方式必须填写");
        }
        FreeTemplateDO templateDO = this.lambdaQuery().eq(FreeTemplateDO::getTempName, tempName).last("limit 1").one();
        if (!ObjectUtils.isEmpty(templateDO)) {
            AssertUtil.assertFalse(!templateDO.getId().equals(templateId), "模板名称不能重复!");
        }
        Integer freeOrNot = request.getFreeOrNot();
        Integer freeOrNotCondition = request.getFreeOrNotCondition();
        List<FreeDeliveryTermsInfoVO> delayedTerms = request.getDelayedTerms();
        List<FreeCarryModeInfoVO> carryModeS = request.getCarryModeS();
        if (templateId == null){
            if (BooleanEnum.TRUE.getCode()==freeOrNot){
                if (CollectionUtils.isEmpty(delayedTerms)){
                    throw new RuntimeException("指定包邮条件不能为空");
                }else{
                    freeOrNotCondition = 1;
                }

            }
            FreeTemplateRequest templateRequest = new FreeTemplateRequest();
            templateRequest.setTempName(tempName);
            templateRequest.setFreeOrNot(freeOrNot);
            templateRequest.setValuationModel(valuationModel);
            templateRequest.setFreeOrNotCondition(freeOrNotCondition);
            FreeTemplateDO freeTemplateDO = FreeTemplateDtoMapper.INSTANCE.request2DO(templateRequest);
            freeTemplateMapper.insertDO(freeTemplateDO);
            Long freeTempId = freeTemplateDO.getId();
            batchInsert(freeTempId, delayedTerms, carryModeS,freeOrNot);
        }else {
            if (BooleanEnum.TRUE.getCode()==freeOrNot){
                if (CollectionUtils.isEmpty(delayedTerms)){
                    throw new RuntimeException("指定包邮条件不能为空");
                }else{
                    freeOrNotCondition = 1;
                }
            }
            FreeTemplateRequest templateRequest = new FreeTemplateRequest();
            templateRequest.setId(templateId);
            templateRequest.setTempName(tempName);
            templateRequest.setFreeOrNot(freeOrNot);
            templateRequest.setValuationModel(valuationModel);
            templateRequest.setFreeOrNotCondition(freeOrNotCondition);
            FreeTemplateDO freeTemplateDO = FreeTemplateDtoMapper.INSTANCE.request2DO(templateRequest);
            freeTemplateMapper.updateDO(freeTemplateDO);
            deliveryTermsService.deletedByTempId(templateId);
            carryModeService.deletedByTempId(templateId);
            batchInsert(templateId, delayedTerms, carryModeS,freeOrNot);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteDOById(String ids) {
        this.deleteDOByIds(ids);
        long templateId = Long.parseLong(ids);
        deliveryTermsService.deletedByTempId(templateId);
        carryModeService.deletedByTempId(templateId);
        return true;
    }

    private void batchInsert(Long templateId, List<FreeDeliveryTermsInfoVO> delayedTerms, List<FreeCarryModeInfoVO> carryModeS,Integer freeOrNot) {
        if (BooleanEnum.TRUE.getCode()==freeOrNot) {
            List<FreeDeliveryTermsDO> termsDOs = delayedTerms.stream().map(item -> {
                FreeDeliveryTermsDO termsDO = new FreeDeliveryTermsDO();
                termsDO.setFreeTemplateId(templateId);
                termsDO.setRegion(item.getRegion());
                termsDO.setPieceNo(item.getPieceNo());
                termsDO.setWeightNo(item.getWeightNo());
                termsDO.setBulkNo(item.getBulkNo());
                termsDO.setPrice(item.getPrice());
                return termsDO;
            }).collect(Collectors.toList());
            deliveryTermsService.batchInsert(termsDOs);
        }
        if (CollectionUtils.isNotEmpty(carryModeS)){
            List<FreeCarryModeDO> carryModeDOS = carryModeS.stream().map(item -> {
                FreeCarryModeDO freeCarryModeDO = new FreeCarryModeDO();
                freeCarryModeDO.setFreeTemplateId(templateId);
                freeCarryModeDO.setRegion(item.getRegion());
                freeCarryModeDO.setFirstPiece(item.getFirstPiece());
                freeCarryModeDO.setFirstWeight(item.getFirstWeight());
                freeCarryModeDO.setFirstBulk(item.getFirstBulk());
                freeCarryModeDO.setFirstPrice(item.getFirstPrice());
                freeCarryModeDO.setSecondPiece(item.getSecondPiece());
                freeCarryModeDO.setSecondWeight(item.getSecondWeight());
                freeCarryModeDO.setSecondBulk(item.getSecondBulk());
                freeCarryModeDO.setSecondPrice(item.getSecondPrice());
                return freeCarryModeDO;
            }).collect(Collectors.toList());
            carryModeService.batchInsert(carryModeDOS);
        }
    }
}
